package com.iteaj.iot.client.mqtt.impl;

import com.iteaj.iot.AbstractProtocol;
import com.iteaj.iot.ProtocolType;
import com.iteaj.iot.client.MultiClientManager;
import com.iteaj.iot.client.mqtt.*;
import com.iteaj.iot.client.protocol.ServerInitiativeProtocol;
import io.netty.handler.codec.mqtt.MqttTopicSubscription;

import java.util.List;

/**
 * Mqtt客户端默认实现
 * @see MqttSubscribeListener spring容器存在此对象将启用此组件
 */
public class DefaultMqttComponent extends MqttClientComponent<DefaultMqttMessage> {

    private static final String NAME = "MQTT<默认>";
    private static final String DESC = "MQTT默认客户端实现";

    public DefaultMqttComponent() { }

    public DefaultMqttComponent(DefaultMqttConnectProperties config) {
        super(config);
    }

    public DefaultMqttComponent(DefaultMqttConnectProperties config, MultiClientManager clientManager) {
        super(config, clientManager);
    }

    public DefaultMqttComponent(DefaultMqttConnectProperties config, MultiClientManager clientManager, MessagePublishListener publishListener) {
        super(config, clientManager, publishListener);
    }

    @Override
    public String getName() {
        return NAME;
    }

    @Override
    public String getDesc() {
        return DESC;
    }

    @Override
    public AbstractProtocol getProtocol(DefaultMqttMessage message) {
        // 使用监听的方式处理
        return new DefaultMqttSubscribeProtocol(message);
    }

    @Override
    protected ServerInitiativeProtocol doGetProtocol(DefaultMqttMessage message, ProtocolType type) {
        throw new UnsupportedOperationException("已经覆写了[getProtocol]方法");
    }


    @Override
    protected List<MqttTopicSubscription> doSubscribe(MqttConnectProperties client) {
        return ((DefaultMqttConnectProperties) client).getTopics();
    }

    /**
     * 为客户端绑定一个监听, 用于监听此客户端得所有topic
     * @param clientId 要绑定得客户端
     * @param listener 监听器
     */
    public MqttListener bindListener(String clientId, MqttListener listener) {
        MqttClient client = this.getClient(clientId);
        if(client == null) {
            throw new MqttClientException("未找到客户端[clientId="+clientId+"]");
        }

        MqttConnectProperties config = client.getConfig();
        if(config instanceof DefaultMqttConnectProperties) {
            if(((DefaultMqttConnectProperties) config).getListener() != null) {
                return ((DefaultMqttConnectProperties) config).getListener();
            } else {
                ((DefaultMqttConnectProperties) config).setListener(listener);
                return listener;
            }
        } else {
            throw new MqttClientException("请使用配置对象["+DefaultMqttConnectProperties.class.getSimpleName()+"]");
        }
    }

    @Override
    public Class<DefaultMqttMessage> getMessageClass() {
        return DefaultMqttMessage.class;
    }

    @Override
    public DefaultMqttMessage createMessage(byte[] message) {
        return new DefaultMqttMessage(message);
    }
}
